// 订单模型
const { Orders } = require('../../../models/order');
// 商品模型
const { Goods } = require('../../../models/good');
// 店铺模型
const { Store } = require('../../../models/store');
// 购物车模型
const { Cart } = require('../../../models/cart');
// 订单号生成
const { orderCode } = require('../../../modules/ordeCode')
// 统一数据返回类
const { DataReturn } = require('../../../common/returnclass');

module.exports = async (req, res) => {
	let { orderform } = req.fields;
	console.log(req.fields);
	let orders = orderform.orders;
	let receiving_address = orderform.receiving_address;
	let price = orderform.price;
	let remark = orderform.remark;
	let order_num = [];
	// 收集错误信息
	let error = [];
	console.log(req.fields);
	orders.forEach(async (item,index)=> {
		console.log(item);
		order_num.push(orderCode());
		let { goods_store,goods_number } = await Goods.findOne({_id: item.goods_id }).select('goods_store goods_number -_id');
		let { send_address, _id } = await Store.findOne({ _id: goods_store }).select('send_address _id');
		console.log(goods_number);
		// 创建订单信息
		Orders.create({
			order_number: order_num[index],
			orders: item,
			order_price: item.goods_msg_price*item.goods_number,
			send_address: send_address,
			receiving_address: receiving_address.address,
			order_belong: item.user_id,
			order_goods: item.goods_id,
			order_store: _id,
			contact: receiving_address.contact,
			mobile: receiving_address.contact_line,
			remark: remark
		}).then(async ()=>{
			return await Cart.deleteOne({_id:item._id});
		}).then(async ()=>{
			return await Goods.updateOne({_id: item.goods_id }, {goods_number:goods_number - 1});
		}).then(res=>{
			console.log('res',res);
		}).catch((err)=>{
			console.log('err',err)
			error.push(err);
		})
	})
	
	if (error.length !=0) return DataReturn.getData(res,200, error,'创建订单失败');
	DataReturn.getData(res,200, order_num,'创建订单成功');

}